package com.hmall.service;

import com.hdmall.business.common.common.ServerResponse;
import com.hmall.mapper.*;
import com.hmall.model.*;
import com.hmall.util.CastHotUtil;
import com.hdmall.business.common.util.SimilarUtil;
import com.hmall.vo.*;
import com.hmall.mapper.MallHistoryMapper;
import com.hmall.mapper.MallProductMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author zhoutao
 */
@Slf4j
@Service
public class MobileHomeService {

    private  MallProductMapper mallProductMapper;

    private  MallHistoryMapper mallHistoryMapper;

    private  MallOrderItemMapper mallOrderItemMapper;

    private  MallBannerMapper mallBannerMapper;

    private  MallHotMapper mallHotMapper;

    private  MallShopMapper mallShopMapper;

    private  SysDeptMapper sysDeptMapper;

    private  MallPriceMapper mallPriceMapper;

    private final BiUserAnalysisMapper biUserAnalysisMapper;


    @Autowired
    public MobileHomeService(MallProductMapper mallProductMapper, MallHistoryMapper mallHistoryMapper, MallOrderItemMapper mallOrderItemMapper, MallBannerMapper mallBannerMapper, MallHotMapper mallHotMapper, MallShopMapper mallShopMapper, SysDeptMapper sysDeptMapper, MallPriceMapper mallPriceMapper, BiUserAnalysisMapper biUserAnalysisMapper) {
        this.mallProductMapper = mallProductMapper;
        this.mallHistoryMapper = mallHistoryMapper;
        this.mallOrderItemMapper = mallOrderItemMapper;
        this.mallBannerMapper = mallBannerMapper;
        this.mallHotMapper = mallHotMapper;
        this.mallShopMapper = mallShopMapper;
        this.sysDeptMapper = sysDeptMapper;
        this.mallPriceMapper = mallPriceMapper;
        this.biUserAnalysisMapper = biUserAnalysisMapper;
    }

    /**
     * @Date 2018/11/9 14:21
     * @Param [count, shopId]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.MallHotVo>>
     * @Description // 截取count 条
     *     热销业务
     */
    public ServerResponse<List<MallHotVo>> listHotProduct(int count, int shopId) {

//        List<MallHot> mallHotList = mallHotMapper.listOnlyHotList(count);
        List<MallHot> mallHotList = mallHotMapper.listOnlyHotListWithoutOtherGrade(count);

        //就10条

        List<MallHotVo> mallHotVoList = new ArrayList<>();

        for(MallHot mallHot : mallHotList){
            String grade = mallPriceMapper.findOne0Grade(mallHot.getProductId());
            if (grade.contains("定重")) {
                if (grade.contains("不")) {
                    grade = "AA不定重";
                } else {
                    grade = "AA定重";
                }
            }


            mallHotVoList.add(CastHotUtil.hotCast(mallProductMapper.selectByProductId(mallHot.getProductId()), mallHot.getSalesVolume(), grade));
        }

        return ServerResponse.createBySuccess(mallHotVoList);
    }


    /**
     * @Date 2018/11/9 14:23
     * @Param [userId, count]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.UserLikeVo>>
     * @Description //
     * 针对所有是商户
     *
     *       猜你喜欢算法:
     *       A对Y的喜好程度 = 求和（A买了X * X与Y的相似度）
     *       https://www.jianshu.com/p/d03fb6d68716
     */
    public ServerResponse<List<UserLikeVo>> listUserLike(int userId, int count){

        //A买了X记为1 不买记为2   X与Y的相似度通过name进行匹配 属性 30%，光泽 20%，纤度/孔数 20%
        // 单合股 10%颜色 10%形状 10%

        //一、列出用户已经购买的产品  查询订单明细表
        List<Integer> buyProductIdList = mallOrderItemMapper.findProductListByUser(userId);

       if(buyProductIdList == null){
           List<MallHot> mallHotList = mallHotMapper.listOnlyHotList(1);
           buyProductIdList = new ArrayList<>();
           buyProductIdList.add(mallHotList.get(0).getProductId());
       }
        //二、列出所有公司生产的产品
        //2018/11/28 用户只能看见A,B,AA不定重，AA定重的产品
        //基数小就不把没有AA定重但是有AA7定重的归类到AA定重
        List<MallProduct> sellProductList = mallProductMapper.selectWithoutOtherGrade();

        //省去查数据库
        Map<Integer, MallProduct> productMap = new HashMap<>();
        for(MallProduct mallProduct : sellProductList){
            productMap.put(mallProduct.getId(), mallProduct);
        }


        Map<MallProduct, Integer> likeMap = new HashMap<>();

        //保证有映射关系
        for(MallProduct sellProduct: sellProductList){
            likeMap.put(sellProduct, 0);
        }
        //相似度求和计算
        for(MallProduct sellProduct : sellProductList){
            String sellName = sellProduct.getName();
            for(Integer buyProductId : buyProductIdList){
                //如果是同一件就放弃
                if(sellProduct.getId().equals(buyProductId)) {
                    continue;
                }
                MallProduct mallProduct = productMap.get(sellProduct.getId());
                String buyName = mallProduct.getName();
                //相似度计算公式
                int result = SimilarUtil.similarValue(sellName, buyName);
                int value = likeMap.get(mallProduct);
                likeMap.put(mallProduct, value + result);
            }
        }

        //进行排序
        List<Map.Entry<MallProduct,Integer>> list = new ArrayList<>(likeMap.entrySet());
        list.sort((o1, o2) -> o2.getValue() - o1.getValue());
        //转换成集合
        List<MallProduct> oldMallProductList = new ArrayList<>();
        for(Map.Entry<MallProduct, Integer> t: list){
            oldMallProductList.add(t.getKey());
        }

        List<MallProduct> subMallProductList = oldMallProductList.subList(0, count);

        List<UserLikeVo> mallProductList = new ArrayList<>();
        for(MallProduct mallProduct : subMallProductList){
            String []str = mallProduct.getName().split(",");
            int length = str[0].length() + 1;
            String name = mallProduct.getName().substring(length, mallProduct.getName().length());
            Integer shopId = mallProductMapper.selectShopIdByProductId(mallProduct.getId());
            String shopName = mallShopMapper.selectByPrimaryKey(shopId).getShopName();
//            MallPrice mallPrice = mallPriceMapper.selectOneByProductId(mallProduct.getId());
            String grade = mallPriceMapper.selectMaxGradeByProductId(mallProduct.getId());
            mallProductList.add(new UserLikeVo(mallProduct.getId(), grade, str[0], name ,shopName, mallProduct.getMainImage(), new BigDecimal(0.0)));
        }

        return ServerResponse.createBySuccess(mallProductList);
    }


    public ServerResponse<List<MallBanner>> listHomeBanner() {
        List<MallBanner> mallBannerList = mallBannerMapper.listPCBanner();
        return ServerResponse.createBySuccess(mallBannerList);
    }

    public ServerResponse<List<MallBanner>> listMeBanner(HttpServletRequest request, String meBanner) {

        //2018/12/21 记录首页PV信息
        recordBiUserAnaysis(request);
        List<MallBanner> mallBannerList = mallBannerMapper.listByType(meBanner);
        return ServerResponse.createBySuccess(mallBannerList);
    }

    public void recordBiUserAnaysis(HttpServletRequest request){

        //安卓在system里面有个android
        //IOS在device_name里面有个IOS
        System.out.println("REQUEST!!!" + request.getParameterMap() + "----" + request.getParameterNames());
        log.info("REQUEST!!!" + request.getParameterMap() + "----" + request.getParameterNames());
        Map<String, String[]> map = request.getParameterMap();
        Set<Map.Entry<String, String[]>> keys = map.entrySet();
        Iterator<Map.Entry<String, String[]>> i = keys.iterator();
        System.out.printf("+__+");
        while (i.hasNext()){
            Map.Entry<String, String[]> it = i.next();
            System.out.println(it.getKey()+":"+Arrays.toString(it.getValue()));
        }


        String ip = UserService.getIP(request);
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH);
        Integer day = calendar.get(Calendar.DAY_OF_MONTH);
        Integer hour = calendar.get(Calendar.HOUR_OF_DAY);
        Integer minute = calendar.get(Calendar.MINUTE);
        Integer second = calendar.get(Calendar.SECOND);
        Integer millionSecond = calendar.get(Calendar.MILLISECOND);
        calendar.set(year, month, day, hour, minute, second);
        calendar.set(Calendar.MILLISECOND, millionSecond);
        Date endTime = calendar.getTime();
        calendar.set(Calendar.MINUTE, -30);
        Date startTime = calendar.getTime();
        String dataType = "PV";
        Integer count = biUserAnalysisMapper.selectCountByIp(ip, startTime, endTime, dataType);
        //没开线程..
        if(count < 10){
            BiUserAnalysis biUserAnalysis = new BiUserAnalysis();
            String deviceName = request.getParameter("device_name");
            String system = request.getParameter("system");
            String deviceType = "PC";
            if(deviceName != null && deviceName.contains("IOS")){
                deviceType = "IOS";
            }
            if(system != null && system.contains("android")){
                deviceType = "ANDROID";
            }
            biUserAnalysis.setDeviceType(deviceType);
            biUserAnalysis.setIp(ip);
            biUserAnalysis.setDataType("PV");
            biUserAnalysis.setCreateTime(new Date());
            biUserAnalysisMapper.insert(biUserAnalysis);
        }
    }

    /**
     * @Date 2018/11/9 14:32
     * @Param []
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.ProductShowVo>>
     * @Description // 产品展示
     */
    public ServerResponse<List<ProductShowVo>> showProduct() {

        List<ProductShowVo> productShowVoList = new ArrayList<>();

        //华鼎商铺id

        Integer hShopId = 1;

        productShowVoList.add(new ProductShowVo("DTY", fineAndPoreUtil("DTY", hShopId), glossUtil("DTY", hShopId)));
        productShowVoList.add(new ProductShowVo("FDY", fineAndPoreUtil("FDY", hShopId), glossUtil("FDY", hShopId)));
        productShowVoList.add(new ProductShowVo("POY", fineAndPoreUtil("POY", hShopId), glossUtil("POY", hShopId)));
        productShowVoList.add(new ProductShowVo("HOY", fineAndPoreUtil("HOY", hShopId), glossUtil("HOY", hShopId)));


        return ServerResponse.createBySuccess(productShowVoList);
    }

    private List<String> glossUtil(String typeName, Integer shopId){

        //所有的光泽
        List<String> glossList;

        glossList = mallProductMapper.listGloss(typeName, shopId);

        Set<String> set = new HashSet<>(glossList);
        glossList.clear();
        glossList.addAll(set);

        set.clear();

        Collections.sort(glossList);

        return glossList;
    }

    private List<String> fineAndPoreUtil(String typeName, Integer shopId){

        List<String> fineAndPoreList;
        fineAndPoreList = mallProductMapper.listFineAndPore(typeName, shopId);

        Set<String> set = new HashSet<>();

        int page = 1;
        StringBuilder strFineAndPore = null;
        List<String> strFineAndPoreList = new ArrayList<String>();
        for (String str : fineAndPoreList) {
            if(page == 1){
                page = 2;
                strFineAndPore = new StringBuilder(str);
            } else{
                page = 1;
                strFineAndPore.append("/").append(str);
                strFineAndPoreList.add(strFineAndPore.toString());
                strFineAndPore = null;
            }
        }

        //去重纤度孔数
        set.clear();
        set.addAll(strFineAndPoreList);
        strFineAndPoreList.clear();
        strFineAndPoreList.addAll(set);

        //排序好纤度孔数顺序

        //String 改int
        List<FineAndPore> intFineAndPoreList = new ArrayList<FineAndPore>();
        for(String strFineAndPoreSub : strFineAndPoreList){
            String [] str = strFineAndPoreSub.split("/");
            int fine = Integer.valueOf(str[0]);
            int pore = Integer.valueOf(str[1]);
            intFineAndPoreList.add(new FineAndPore(fine, pore) );
        }



        //对结构排序
        intFineAndPoreList.sort((o1, o2) -> {
            if (o1.getFine() == o2.getFine()) {
                return o1.getPore() - o2.getPore();
            }
            return o1.getFine() - o2.getFine();
        });

        //重新得到串
        List<String> strFineAndPoreListRe = new ArrayList<>();
        for (FineAndPore fineAndPore : intFineAndPoreList) {
            String strRe = fineAndPore.getFine() + "/" + fineAndPore.getPore();
            strFineAndPoreListRe.add(strRe);
        }

        return strFineAndPoreListRe;
    }

    /**
     * @Date 2018/11/9 14:30
     * @Param [count]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.MallShopVo>>
     * @Description // 展示推荐商铺
     */
    public ServerResponse<List<MallShopVo>> showShop(Integer count) {

        List<MallShopVo> mallShopVoList = new ArrayList<>();

        List<MallShop> mallShopList = mallShopMapper.selectLimit(count);

        int [] customizedStatus= new int[]{0, 1, 2, 2, 1, 0};
        int [] tradeStatus = new int[]{2, 1, 0, 0, 2, 1};
        String[] customized = new String[]{"40", "50", "45", "50", "55", "60"};
        String[] trade = new String[]{"30", "40", "35", "37", "41", "33"};
        String[] logiLoss = new String[]{"40", "50", "55", "65", "54", "47"};
        Double[] shopRank = new Double[]{4.4, 4.5, 4.6, 4.3, 4.8, 4.7};
        int[] productNum = new int[]{1001, 998, 448, 558, 654, 700};

        int flag = -1;
        for(MallShop mallShop : mallShopList) {
            flag++;
            MallShopVo mallShopVo = new MallShopVo();
            mallShopVo.setShopId(mallShop.getShopId());
            mallShopVo.setShopName(mallShop.getShopName());
            String deptName = sysDeptMapper.selectNameById(mallShop.getDeptId());
            mallShopVo.setDeptName(deptName);
            mallShopVo.setShopLogo(mallShop.getShopLogo());

            //每一个商家的产品
            List<Map<String, String>> productList = new ArrayList<>();
            List<MallProduct> threeProductList = mallProductMapper.selectLimit3(mallShop.getShopId());
            for (int i = 0; i <= 2; i++) {
                Map<String, String> mapList = new HashMap<>();
                mapList.put("productImg", threeProductList.get(i).getMainImage());
                mapList.put("productId", String.valueOf(threeProductList.get(i).getId()));
                productList.add(mapList);

            }

            mallShopVo.setProductList(productList);

            mallShopVo.setCustomized(customized[flag]);
            mallShopVo.setCustomizedStatus(customizedStatus[flag]);
            mallShopVo.setShopRank(shopRank[flag]);
            mallShopVo.setTrade(trade[flag]);
            mallShopVo.setTradeStatus(tradeStatus[flag]);
            mallShopVo.setProductNum(productNum[flag]);
            mallShopVo.setLogiLoss(logiLoss[flag]);

            mallShopVoList.add(mallShopVo);
        }

        return ServerResponse.createBySuccess(mallShopVoList);

    }

}


